import { _decorator, Label, Button, Node, Vec3, v3 } from 'cc';
import { BasePanel } from '../../../../scripts/libs/ui/BasePanel';
import { BindButton } from '../../../../scripts/libs/rxjs/cc3/BindButton';
import { ReactiveProperty } from '../../../../scripts/libs/rxjs/cc3/ReactiveProperty';
import { FeatureKey } from '../../../../scripts/managers/DevConfig';
import { lm } from '../../LobbyManager';
import { i18n } from '../../../../scripts/i18n';
import { SpriteFrame } from 'cc';
import { Sprite } from 'cc';
import { forkJoin, Observable } from 'rxjs';
import { TweenToStart } from '../../../../scripts/libs/rxjs/cc3/TweenStart';
import { SpriteAtlas } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('FeatureUnlockPanel')
export class FeatureUnlockPanel extends BasePanel {

    featureKey = ReactiveProperty.Create<FeatureKey>(null);

    @property(Node)
    mainNode: Node = null;

    @property(Button)
    continueButton: Button = null;

    @property(Sprite)
    mainSprite: Sprite = null;

    @property(Label)
    titleLabel: Label = null;

    @property(Label)
    descLabel: Label = null;

    @property(SpriteAtlas)
    atlas: SpriteAtlas = null;

    willBind(): void {
        lm.featureUnlockPanelOpened.value = true;
        this.adaptive();
    }

    useObserves() {
        return [
            this.featureKey.subscribe(this.refresh.bind(this)),
            BindButton(this.continueButton).subscribe(this.continueButtonClicked.bind(this))
        ];
    }

    adaptive() {
        this.mainNode.setScale(v3(Vec3.ONE).multiplyScalar(lm.getAdaptiveScale()));
    }

    openPanelAnim(): Observable<any> {
        return forkJoin([
            TweenToStart(this.ensureUIOpacity(), .2, { opacity: 255 }, { easing: 'expoOut' }),
            TweenToStart(this.mainNode, .4, { scale: lm.getAdaptiveScaleV3() }, { easing: 'backOut' }),
        ]);
    }

    closePanelAnim(): Observable<any> {
        this.ensureUIOpacity();
        return forkJoin([
            TweenToStart(this.ensureUIOpacity(), .2, { opacity: 0 }, { easing: 'expoIn' }),
            TweenToStart(this.mainNode, .2, { scale: v3(.5, .5, .5) }, { easing: 'backIn' }),
        ]);
    }

    onDestroyView(): void {
        lm.featureUnlockPanelOpened.value = false;
    }

    refresh() {
        if (this.featureKey.value == null) return;
        this.mainSprite.spriteFrame = this.atlas.getSpriteFrame(`feature/${this.featureKey.value}`);
        this.titleLabel.string = i18n.t(`feature.${this.featureKey.value}.title`);
        this.descLabel.string = i18n.t(`feature.${this.featureKey.value}.desc`);
    }

    continueButtonClicked() {
        FeatureUnlockPanel.CloseProcess(null, 'close');
    }

}

